﻿using AutoMapper.Internal.Mappers;
using ERP.Permissions;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using Volo.Abp.OpenIddict;

namespace ERP.MaterialTypes
{
    [Authorize(ERPPermissions.MaterialType.Default)]
    public class MaterialTypeService : ERPAppService
    {
        public IRepository<MaterialType> _materialTypeRepository { get; set; }

        [Authorize(ERPPermissions.MaterialType.Create)]
        public async Task CreateAsync(MaterialTypeCreateInput input)
        {
            var materialType = new MaterialType(input.Name, input.Description);
            await _materialTypeRepository.InsertAsync(materialType);
        }

        [Authorize(ERPPermissions.MaterialType.Edit)]
        public async Task UpdateAsync(Guid id, MaterialTypeUpdateInput input)
        {
            var materialType = await _materialTypeRepository.GetAsync(t => t.Id == id);
            materialType.Update(input.Name, input.Description);
            await _materialTypeRepository.UpdateAsync(materialType);
        }

        [Authorize(ERPPermissions.MaterialType.Delete)]
        public async Task DeleteAsync(Guid id)
        {
            await _materialTypeRepository.DeleteAsync(t => t.Id == id);
        }

        [Authorize(ERPPermissions.MaterialType.Default)]
        public async Task<MaterialTypeDto> GetAsync(Guid id)
        {
            var materialType = await _materialTypeRepository.GetAsync(t => t.Id == id);
            return ObjectMapper.Map<MaterialType, MaterialTypeDto>(materialType);
        }

        [Authorize(ERPPermissions.MaterialType.Default)]
        public async Task<PagedResultDto<MaterialTypeDto>> GetListAsync(GetMaerialTypeListInput input)
        {
            var queryable = (await _materialTypeRepository.GetQueryableAsync())
                //.WhereIf(!string.IsNullOrWhiteSpace(input.Name), t => t.Name == input.Name)
                .WhereIf(!string.IsNullOrWhiteSpace(input.Name), t => t.Name.Contains(input.Name))
                .WhereIf(!string.IsNullOrWhiteSpace(input.Description), t => t.Description.Contains(input.Description));

            var materialTypes = await AsyncExecuter.ToListAsync(queryable.Skip(input.SkipCount).Take(input.MaxResultCount));
            var list = ObjectMapper.Map<List<MaterialType>, List<MaterialTypeDto>>(materialTypes);

            var totalCount = await AsyncExecuter.CountAsync(queryable);


            return new PagedResultDto<MaterialTypeDto>(totalCount, list);
        }

        //public async Task<string> Greet(string content)
        //{
        //    await Task.Delay(1000);
        //    return "hello，" + content;
        //}
    }
}
